package com.zdkj.edge.door.demo.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.zdkj.edge.door.demo.conf.AdmsConf;
import com.zdkj.edge.door.demo.model.api.*;
import com.zdkj.edge.vehicle.demo.model.api.*;
import com.zdkj.edge.door.demo.service.AdmsApiBase;
import com.zdkj.edge.door.demo.service.AdmsApiService;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
public class AdmsApiServiceImpl extends AdmsApiBase implements AdmsApiService {


  public AdmsApiServiceImpl(AdmsConf admsConf) {
    super(admsConf);
  }


  /**
   * 获取设备列表
   * @param request 查询参数
   * @return 设备列表响应
   */
  @Override
  public ApiResponse<List<ApiDeviceListResponse>> getDeviceList(ApiDeviceListRequest request) {
    // 将请求对象转为 Map
    Map<String, Object> paramMap = new HashMap<>();
    paramMap.put("DeviceName", request.getDeviceName());
    paramMap.put("LocationId", request.getLocationId());
    paramMap.put("DeviceId", request.getDeviceId());

    // 请求路径
    String url = "/api/FaceHQ/GetDeviceList";

    // 发起请求并解析为 ApiResponse<List<ApiDeviceListResponse>>
    Object rawResult = doPostJsonResult(url, paramMap);
    String json = JSON.toJSONString(rawResult);
    return JSON.parseObject(json, new com.alibaba.fastjson.TypeReference<ApiResponse<List<ApiDeviceListResponse>>>() {});
  }


  /**
   * 不推荐主动调用 login，已由父类内部自动处理
   */
  @Override
  public ApiResponse<ApiLoginData> login(ApiLoginRequest request) {
    throw new UnsupportedOperationException("请通过 getApiToken() 自动登录");
  }



  /**
   * 可选：暴露当前 token
   */
  @Override
  public String getApiToken() {
    return super.getValidToken();
  }



  /**
   * 获取近期通行记录
   */
  @Override
  public ApiResponse<List<ApiAccessRecordResponse>> getAccessRecordList(ApiAccessRecordRequest request) {
    // 请求路径
    String url = "/api/visitor/GetRecordList";

    // 将请求对象转换为 Map
    @SuppressWarnings("unchecked")
    Map<String, Object> paramMap = JSON.parseObject(JSON.toJSONString(request), Map.class);

    // 发起 POST 请求
    Object rawResult = doPostJsonResult(url, paramMap);
    String json = JSON.toJSONString(rawResult);
    // 解析响应为 ApiResponse<List<ApiAccessRecordResponse>>
    TypeReference<ApiResponse<List<ApiAccessRecordResponse>>> typeRef = new TypeReference<ApiResponse<List<ApiAccessRecordResponse>>>() {};
    ApiResponse<List<ApiAccessRecordResponse>> response =
        JSON.parseObject(json, typeRef.getType());

    // 日志记录
    if (response == null || response.getTag() != 1) {
      log.error("【ADMS】获取通行记录失败，响应内容：{}", json);
    } else {
      log.info("【ADMS】成功获取通行记录，总数：{}", response.getTotal());
    }

    return response;
  }


}
